$(function () {
	refreshedModel("");
	var viewType = $('#viewType').val();
	if(viewType == 'wwb'){
		$('#groupTr').show();
	}else{
		$('#groupTr').hide();
	}
});
/**
 * 创建table头
 * 
 * @returns
 */
var builderTh = function (){
	$("#leftTable").empty();
	var viewType =$('#viewType').val();
	var temp = $('#dataJson').val();
	var dataJson = eval('('+temp+')');
	if(viewType == 'gxmx'){
	       tr = '<tr><th class="gx_col" style="text-align: center;" scope="col"  >中文名称</th><th class="gx_enCol" scope="col">英文名称</th><th class="gx_enCol" scope="col">对应库表</th><th class="gx_color" scope="col">线条颜色</th><th class="gx_wide" scope="col">线条粗细</th><th class="gx_ext"  scope="col">可扩展性</th><th class="gx_opr" style="text-align: center;" scope="col">操作</th> </tr>';
	}else if(viewType == 'zywd'){
		 tr = '<tr><th class="zywd_col" scope="col"  >中文名称</th><th class="zywd_enCol" scope="col">英文名称</th><th class="zywd_enCol" scope="col">对应库表</th><th class="zywd_opr" style="text-align: center;" scope="col">操作</th></tr>';
	}else{
	       tr = '<tr><th class="col" scope="col"  >中文名称</th><th class="enCol" scope="col">英文名称</th><th class="enCol" scope="col">对应库表</th><th class="opr" style="text-align: center;" scope="col">操作</th></tr>';
	}
	$("#leftTable").append(tr);
	builderTop(0, dataJson, 'block',viewType);
}
/**
 * 构建模型展示树
 * 
 * @param count
 *            右移像素
 * @param dataJSon
 *            json数据
 * @param dis
 *            初始化显隐性
 * @param viewType
 *            模型视图类型
 * @returns
 */
var builderTop = function (count, dataJSon, dis,viewType) {
    var table = $("#leftTable");
    var className = dataJSon.className;
    var manuIcon = dataJSon.manuIcon;
    var modelIcon16 = dataJSon.modelIcon16;
    var classTitle = dataJSon.classTitle;
    var tableName = dataJSon.tableName;
    var linkColor = dataJSon.linkColor;
    if(linkColor != undefined && linkColor != 'undefined' && linkColor != ''){
    	linkColor = linkColor.replace(/\s/g, "");
    }
    var linkThickness = dataJSon.linkThickness;
    var fullName = dataJSon.fullName;
    var tr = $("<tr>");
    if (dis == 'block') {
        tr.show();
    } else {
        tr.hide();
    }
    var td1 ;
    if(viewType == 'gxmx'){
    	td1 = $("<td class='gx_col'>");
    }else if(viewType == 'zywd'){
    	td1 = $("<td class='zywd_col'>");
    }else{
    	td1 = $("<td class='col'>");
    }
    
    var hiddenIn = $('<input type ="hidden" id="' + fullName + '" value = "' + fullName + '"/>');
    td1.append(hiddenIn);
    var div = $("<div>");

    div.attr('style', 'padding-left:' + count + 'em');
    div.append('<span class="spanl fuxuan"><input id="' + classTitle + '" value="' + classTitle + '" type="checkbox" onclick="checkBoxChoose(this);event.cancelBubble=true;"/></span><span class="spanl tbimg"></span><span class="spanl tbname">' + className + '</span>');

    var children = dataJSon.submenu;
    
    if (children.length > 0) {
    	var span1 ;
        div.addClass('tbdiv');
        if(fullName == 'RelRelation'){
        	span1 = $('<span class="spanl"></span><span class="spanr"><s class="tbdown"></s></span>');
        }else{
        	span1 = $('<span class="spanl"><a href="javascript:void(0);" class="tbedit"  onclick="updateName(this);event.cancelBubble=true;"></a></span><span class="spanr"><s class="tbdown"></s></span>');
        }
        div.append(span1);
    } else {
    	var span1 ;
    	if(fullName == 'RelRelation'){
        	span1 = $('<span class="spanl"></span><span class="spanr"><s class="tbdown"></s></span>');
        }else{
        	span1 = $('<span class="spanl"><a href="javascript:void(0);" class="tbedit"  onclick="updateName(this);event.cancelBubble=true;"></a></span><span style="display:none" class="spanr"><s class="tbdown"></s></span>');
        }
        div.append(span1);
    }
    div.bind("click",function () {
    	openOrCloseMenu(this);
    });
    td1.append(div);
    tr.append(td1);
    
    var td2 ;
    if (viewType == 'gxmx') {
    	tr.append('<td class="gx_enCol">' + classTitle + '</td><td class="gx_enCol">' + tableName + '</td>');
    	if(fullName == 'RelRelation'){
    		var td2 = '<td class="gx_color" ></td><td class="gx_wide" ></td><td class="gx_ext" ></td><td class="gx_opr"></td>';
    	}else{
	    	var td3 = $('<td class="gx_color">');
	        var input = $('<input  id="'+classTitle+'_linkColor" value="' + linkColor + '" >');
	        td3.append(input);
	        tr.append(td3);
	        input.spectrum({
	            chooseText: "确定",
	            cancelText: "取消",
	            preferredFormat: "rgb",
	            showInput: true,
	            showPalette: true,
	            palette:[
	                ["#000000", "#434343", "#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3", "#ffffff"],
	                        ["#980000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#4a86e8", "#0000ff", "#9900ff", "#ff00ff"],
	                        ["#e6b8af", "#f4cccc", "#fce5cd", "#fff2cc", "#d9ead3", "#d9ead3", "#c9daf8", "#cfe2f3", "#d9d2e9", "#ead1dc"],
	                        ["#dd7e6b", "#ea9999", "#f9cb9c", "#ffe599", "#b6d7a8", "#a2c4c9", "#a4c2f4", "#9fc5e8", "#b4a7d6", "#d5a6bd"],
	                        ["#cc4125", "#e06666", "#f6b26b", "#ffd966", "#93c47d", "#76a5af", "#6d9eeb", "#6fa8dc", "#8e7cc3", "#c27ba0"],
	                        ["#a61c00", "#cc0000", "#e69138", "#f1c232", "#6aa84f", "#45818e", "#3c78d8", "#3d85c6", "#674ea7", "#a64d79"],
	                        ["#85200c", "#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#1155cc", "#0b5394", "#351c75", "#741b47"],
	                        ["#5b0f00", "#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#1c4587", "#073763", "#20124d", "#4c1130"]
	                ],
	            hide: function(tinycolor) {
	            	updateLinkWide(input[0],"linkColor");
	            }
	        });
	        // 在这里添加判断是否可以扩展的逻辑
	        if (fullName.indexOf("RelConnect") > -1) {
	            td2 = ('<td class="gx_wide"><input type="text" style="width:40px;" maxlength="3"  name="attribute_width" class="tbinpt"  id="' + classTitle + '_width" value="' + linkThickness + '" onkeypress="return common.num_int(this,event)" onchange = "updateLinkWide(this,\'width\')"/></td><td class="gx_ext">可扩展</td><td class="gx_opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'gxmx\')">属性维护</a><br/><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="maintainEnv(this)">适用环境</a></td>');
	            // td2.html("可扩展");
	        } else {
	            td2 = ('<td class="gx_wide"><input type="text" style="width:40px;" maxlength="3" name="attribute_width" class="tbinpt" id="' + classTitle + '_width" value="' + linkThickness + '" onkeypress="return common.num_int(this,event)" onchange = "updateLinkWide(this,\'width\')"/></td><td class="gx_ext">不可扩展</td><td class="gx_opr"><a href="javascript:void(0);"  onclick="maintainEnv(this)">适用环境</a></td>');
	            // td2.html("不可扩展");
	        }
    	}
    }else if (viewType == 'zywd'){
    	tr.append('<td class="zywd_enCol">' + classTitle + '</td><td class="zywd_enCol">' + tableName + '</td>');
    	//资源维度（字典）的模型不可以存在子模型，因此只能新建跟模型、不可以在跟模型下新建自模型
    	if(classTitle =='ResSuperDim'){
    		td2 = ('<td class="zywd_opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}else{
    		td2 = ('<td class="zywd_opr"><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}
    }else if(viewType == 'zydx'){ 
    	tr.append('<td class="enCol">' + classTitle + '</td><td class="enCol">' + tableName + '</td>');
    	if(classTitle =='ResObject'){
    		 td2 = ('<td class="opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}else{
    		td2 = ('<td class="opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}
    } else if(viewType == 'wwb'){
    	tr.append('<td class="enCol">' + classTitle + '</td><td class="enCol">' + tableName + '</td>');
    	if(classTitle =='ResStructure'){
    		td2 = ('<td class="opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}else{
    		td2 = ('<td class="opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>');
    	}
    }else {
    	alert("出现了未知"+viewType+"类型的"+classTitle+"对象，请联系管理员!");
    }
    tr.append(td2);
    table.append(tr);

    if (children.length > 0) {
        count++;
        $.each(children, function (i, chils) {
// if(count == 1){
// builderTop(count, chils, 'block',viewType);
// }else{
// builderTop(count, chils, 'none',viewType);
// }
        	builderTop(count, chils, 'none',viewType);
        });
    }
};


/**
 * 根据类名获取类的节点
 * @param className
 */
var findDataByClsName = function (className){
    var currentDate ;
    var table = $('#leftTable');
    $('table tr').each(function(i ,evTr){
        try{
            var currentVal = $(evTr).find(">td input[type='hidden']").val();
            var d =currentVal.length-className.length-1;
           if((d>0&&currentVal.lastIndexOf('.'+className)==d)||currentVal == className){
               currentDate =  $(evTr).find(">td input[type='hidden']").next()[0];
               return false;
           }
        }catch (e){

        }
    });
   return currentDate;
};



/**
 * 获取所有的上级节点
 * @param data
 */
var findCanOp= function (className){
	var data = findDataByClsName(className);
    var tempData = [];
    var currentCls = $(data).prev().val();
    $(data).attr("class", "tbdiv");
    tempData.push(data);
    var tr = $(data).parent().parent().prev();
    while(tr.length == 1){
        try{
            var chiVal = tr.find(">td input[type='hidden']").val();
            if (currentCls.indexOf(chiVal+'.') == 0 && 1 == compareCount(chiVal, currentCls)) {
                currentCls = chiVal;
                var currentData = tr.find(">td input[type='hidden']").next();
                currentData.attr("class", "tbdiv");
                tempData.push(currentData[0]);
                //tempData.push(tr);

            }
            tr = tr.prev();
        }catch (e){
            tr = tr.prev();
        }
    }
    
    return tempData;
    //alert(tempData.length);
};

/**
 * 倒序打开菜单
 * @param tempData
 */
var opMenu = function (className){
	var tempData = findCanOp(className);
    for(var i=tempData.length-1;i>=0;i--){
        openOrCloseMenu(tempData[i])
    }
};

/**
 * 打开或关闭下级菜单
 * 
 * @param data
 * @returns
 */
var openOrCloseMenu = function (data){
	 var classVal = $(data).attr("class");
     if (classVal == 'tbdiv tdcurrent') {
         // 关闭子菜单
         $(data).attr("class", "tbdiv");
         var parVal = $(data).parent().children('input[type="hidden"]').val();
         /* alert(inp); */
         var par = $(data).parent().parent();
         var nextTr = par.nextAll('tr');
         nextTr.each(function (m, chilNode) {
             var chiVal = $(chilNode).find(">td input[type='hidden']").val();
             if (chiVal.indexOf(parVal) == 0) {
            	 $(chilNode).find(">td div[class='tbdiv tdcurrent']").attr("class", "tbdiv");
                 $(chilNode).hide();
             }
         });
     } else {
         // 打开子菜单
         var parVal = $(data).parent().children('input[type="hidden"]').val();
         /* alert(inp); */
         var par = $(data).parent().parent();
         var nextTr = par.nextAll('tr');
         var flag = 'false';
         nextTr.each(function (m, chilNode) {
             var chiVal = $(chilNode).find(">td input[type='hidden']").val();
             if (chiVal.indexOf(parVal) == 0 && 1 == compareCount(parVal, chiVal)) {
                 // $(chilNode).display('bolck');
                 // $(chilNode).css('display',"block");
                 flag = 'true';
                 $(chilNode).show();
             }
         });
         if (flag == 'true') {
             $(data).attr("class", "tbdiv tdcurrent");
         }
     }
     setTrWidth();
}
/**
 * 比较str2中某个字母是否比str1中某个字母出现的次数大一
 * 
 * @param str1
 * @param str2
 * @returns {number} 1 大一 0 不大于1
 */
var compareCount = function (str1, str2) {
    var chilCount = str_repeat(str2);
    var parCount = str_repeat(str1);
    if (parCount + 1 == chilCount)
        return 1;
    else
        return 0;
}
/**
 * 统计字符串中某个字母出现的次数
 * 
 * @param str
 * @returns {number}
 */
var str_repeat = function (str) {
    var sub = ".";
    var k = 0, sum = 0;
    k = str.indexOf(sub);
    while (k > -1) {
        sum += 1;
        k = str.indexOf(sub, k + 1);
    }
    return sum;
};
/**
 * 修改模型的classname属性
 * 
 * @param data
 */
var updateName = function (data) {
    var currentData = $(data);
    var className = currentData.attr('class');
    var span = currentData.parent().prev();
    var classTitle = currentData.parent().parent().prev().val();
    classTitle = classTitle.substring(classTitle.lastIndexOf('.')+1);
    var tempVal = span.html();
    span.empty();
    span.append('<input id="'+classTitle+'_classDescr" class="tbinpt" type="text"  name="' + tempVal + '"  value="' + tempVal + '"onclick = "event.cancelBubble=true;" onblur="checkVal(this)"/>');
    
    span.children('input').focus().val(tempVal);
    currentData.parent().empty();
};

/**
 * 检查是否允许修改模型类名
 * 
 * @param data
 */
var checkVal = function (data) {
    var currentData = $(data).parent();
    var classTitle = $(data).parent().parent().parent().next().html();
    var oldVal = $(data).attr('name');
    var newVal = $(data).val().replace(/(^\s*)|(\s*$)/g, '');
    if(newVal ==''){
    	currentData.html(oldVal);
    }else if (oldVal == newVal) {
        // 没有做任何修改
        currentData.html(oldVal);
    } else if(newVal.length>9){
    	alert("中文名称不能多于9个！");
    	return ;
    }else if(isExistProName('update',classTitle,newVal)){
    	alert("已经存在此名称！");
    	return ;
    }else {
        // alert("不同");
        // 需要同步到后台数据库
    	
    	var flag =  updateLinkWide(data,"classDescr");
    	if(flag){
    		currentData.html(newVal);
    	}else{
    		alert("修改失败！");
    	}
    }
    currentData.next().html('<a href="javascript:void(0);" class="tbedit"  onclick="updateName(this);event.cancelBubble=true;"></a>');
};
/**
 * 选定复选框
 * 
 * @param data
 * @returns
 */
var checkBoxChoose = function (data) {
    var flag = $(data).is(':checked');
    // 全部取消勾选
    var classTitle = $(data).parent().parent().prev().val();
    var tr = $(data).parent().parent().parent().parent();
    tr.nextAll().each(function (i, trNode) {
        var childTitle = $(trNode).find('> td input[type="hidden"').val();
        if (childTitle.indexOf(classTitle) == -1) {
            return;
        } else {
            var chilCheck = $(trNode).children('td:first-child').find('>div span input[type="checkbox"]');
            var a = chilCheck.val();
            chilCheck.attr('checked', flag);
        }
    });
};
/**
 * 追加新节点
 * 
 * @param data
 */
var newNode = function (data){
    var className = $(data).parent().parent().children().first().find('> div span ').eq('2').html();
    var classTitle = $(data).parent().parent().children().first().find("input[type='hidden']").val();
    var viewType = $('#viewType').val();
    $('#isSession').attr('checked',true);
    if(viewType != 'wwb'){
        $('#isSession').attr('disabled','disabled');
        $('#groupMassage').hide();
    }
    $('#parVal').val(className);
// $('#linkType').val("需要从后台获取");
// $('#relationDescr').val("模型说明，需要从后台获取");
    $('#parVal').attr('name',classTitle);
    document.getElementById('light').style.display='block';
    document.getElementById('fade').style.display='block';
    var divLi = document.getElementById('light');
    var height = getHeight();
//    alert(height);
    if(viewType == 'gxmx'){
    	$(divLi).height(340);
    	$(divLi).css("top",(height-170)+'px');
    }else if(viewType == 'zydx' || viewType == 'zywd'){
    	$(divLi).height(210);
    	$(divLi).css("top",(height-105)+'px');
    }else if(viewType == 'wwb'){
    	$(divLi).height(240);
    	$(divLi).css("top",(height-120)+'px');
    }
    var viewType = $("#viewType").val();
    $('#linkColor').val("");
    if(viewType == 'gxmx'){
    	$('#linkWide_tr').show();
    	$('#link_tr').show();
    	$('#linkType_tr').show();
    	$('#relationDescr_tr').show();
    	$('#linkColor').val("rgb(255, 128, 0)");
    	$('#linkColor').spectrum({
            chooseText: "确定",
            cancelText: "取消",
            preferredFormat: "rgb",
            showInput: true,
            showPalette: true,
            palette:[
                ["#000000", "#434343", "#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3", "#ffffff"],
                        ["#980000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#4a86e8", "#0000ff", "#9900ff", "#ff00ff"],
                        ["#e6b8af", "#f4cccc", "#fce5cd", "#fff2cc", "#d9ead3", "#d9ead3", "#c9daf8", "#cfe2f3", "#d9d2e9", "#ead1dc"],
                        ["#dd7e6b", "#ea9999", "#f9cb9c", "#ffe599", "#b6d7a8", "#a2c4c9", "#a4c2f4", "#9fc5e8", "#b4a7d6", "#d5a6bd"],
                        ["#cc4125", "#e06666", "#f6b26b", "#ffd966", "#93c47d", "#76a5af", "#6d9eeb", "#6fa8dc", "#8e7cc3", "#c27ba0"],
                        ["#a61c00", "#cc0000", "#e69138", "#f1c232", "#6aa84f", "#45818e", "#3c78d8", "#3d85c6", "#674ea7", "#a64d79"],
                        ["#85200c", "#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#1155cc", "#0b5394", "#351c75", "#741b47"],
                        ["#5b0f00", "#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#1c4587", "#073763", "#20124d", "#4c1130"]
                ],
            hide: function(tinycolor) {
// alert(tinycolor);
            }
        });
    	
    }else{
    	$('#link_tr').hide();
    	$('#linkWide_tr').hide();
    	$('#linkType_tr').hide();
    	$('#relationDescr_tr').hide();
    }
    $("#submitForm").bind("click",function(){
    	// 点击确定按钮
    	getRe(data);
    });
    $("#closeDiv").bind("click",function(){
    	// 点击取消按钮
    	$("#submitForm").unbind("click");
// $('#classTitleTr').removeClass();
// $('#classNameTr').removeClass();
    	removeAllClass();
    	$('#classTitle').val("");
    	$('#className').val("");
    	$('#linkWide').val("");
    	$('#linkType').val("");
    	$('#shunxu').val("");
    	$('#linkColor').val("");
    	$('#relationDescr').val("");
    	document.getElementById('light').style.display='none';
        document.getElementById('fade').style.display='none';
    });
//    setSize();
};
/**
 * 获取弹出层在屏幕的的实际位置
 * @returns {Number}
 */
function getHeight(){
	 var liulnaqiHei =  (parent.browerHei)/2; //浏览器可视化高度
//     var divHeiht =  $("#DialogDiv").height()/2;
//     var divHeiht =  top.window.innerHeight;
     var scroHei = $(window.parent).scrollTop();  //滚动条高度
//     var parh = 52;
//     alert("浏览器可视化高度 ："+liulnaqiHei+"\n"+"滚动条高度"+scroHei);
//     $("#DialogDiv").css("top", (scroHei+liulnaqiHei-parh)+"px");

    return scroHei+liulnaqiHei+43;
}
/**
 * 移除所有的错误提示样式
 * 
 * @returns
 */
var removeAllClass = function (){
	$('#classTitleTr').removeClass();
	$('#classNameTr').removeClass();
	$('#shunxuTr').removeClass();
	$('#linkWide_tr').removeClass();
};
/**
 * 新增时的检查
 */
function getRe(data){
	removeAllClass();
	var className = $('#className').val();
    var classTitle =$('#classTitle').val();
    var superClassTitle = $('#parVal').attr('name');
    var isSession = $("#isSession").is(':checked');
    var shunxu = $('#shunxu').val();
    var group = $('#group').val();
    var linkColor = $('#linkColor').val().replace(/\s/g, "");
    var linkWide = $('#linkWide').val();
    var viewType = $('#viewType').val();
    
    var linkType = $('#linkType').val();
    var relationDescr = $('#relationDescr').val();
    
    var isFormat = checkIsFormat(viewType,className,classTitle,shunxu,linkWide);
    if(!isFormat){
    	return ;
    }
    checkClassMessage(viewType,superClassTitle,className,classTitle,isSession,shunxu,group,linkColor,linkWide,linkType,relationDescr,data);
	
};


/**
 * 检查输入是否符合输入规定
 * 
 * @param viewType
 * @param className
 * @param classTitle
 * @param shunxu
 * @param linkWide
 * @returns
 */
var checkIsFormat =function (viewType,className,classTitle,shunxu,linkWide){
	var flag = true;
	// 判断是否为空或已经存在
	if(viewType == 'gxmx'){
		if(linkWide.replace(/(^\s*)|(\s*$)/g,'')==""){
		    $('#linkWide_tr').addClass("errortd");
		    $('#linkWide_tr').find('td:last-child').find('div').html("不能为空!");
		    flag =false;
	    }
		if (! /^\d+$/.test(linkWide)) {
			//不全是数字
			$('#linkWide_tr').addClass("errortd");
			$('#linkWide_tr').find('td:last-child').find('div')
					.html("必须输入数字！！");
			flag = false;
		}
	}
	
	// 检查类名和标题名称是否已经存在
	if(''==className.replace(/(^\s*)|(\s*$)/g,'') || ''==classTitle.replace(/(^\s*)|(\s*$)/g,'')){
		if(''==className.replace(/(^\s*)|(\s*$)/g,'')){
		    $('#classNameTr').addClass("errortd");
			$('#classNameTr').find('td:last-child').find('div').html("不能为空！");	
		}
		if(''==classTitle.replace(/(^\s*)|(\s*$)/g,'')){
			$('#classTitleTr').addClass("errortd");
			$('#classTitleTr').find('td:last-child').find('div').html("不能为空！");	
		 }
	}
	if(!flag){
		return flag;
	}
	 if(!/^[a-zA-Z][0-9a-zA-Z]*$/.test(classTitle.replace(/(^\s*)|(\s*$)/g,''))) {
		 //判断是否包含汉字
		 $('#classTitleTr').addClass("errortd");
		   $('#classTitleTr').find('td:last-child').find('div').html("只能为字母和数字，且不能以数字开头！");
		   flag =false;
		 
	 }else if(classTitle.replace(/(^\s*)|(\s*$)/g,'').indexOf("Res")!=0 && classTitle.replace(/(^\s*)|(\s*$)/g,'').indexOf("Rel")!=0){
		//是否已Res或rel开头
		 $('#classTitleTr').addClass("errortd");
		 $('#classTitleTr').find('td:last-child').find('div').html("以Res或Rel开头!");
		 flag =false;
	 }else  if(classTitle.replace(/(^\s*)|(\s*$)/g,'').length==3 || classTitle.replace(/(^\s*)|(\s*$)/g,'').length >29){
		//
		$('#classTitleTr').addClass("errortd");
		 $('#classTitleTr').find('td:last-child').find('div').html("长度在4-29之间!");
		 flag =false;
	}
	if(className.replace(/(^\s*)|(\s*$)/g,'').length>9){
		$('#classNameTr').addClass("errortd");
		$('#classNameTr').find('td:last-child').find('div').html("中文名称个数不能多于9个！");
		flag =false;
	}
	if(isExistProName('add',classTitle,className)){
		$('#classNameTr').addClass("errortd");
		$('#classNameTr').find('td:last-child').find('div').html("已经存在此名称！");
		flag =false;
	}
	if(shunxu.replace(/(^\s*)|(\s*$)/g,'')!="" && ! /^[1-9]+(\.[0-9]+)*$/.test(shunxu.replace(/(^\s*)|(\s*$)/g,''))){
	   	$('#shunxuTr').addClass("errortd");
	   	$('#shunxuTr').find('td:last-child').find('div').html("顺序格式错误!");
	   	flag =false;
	}
	return flag;
};

/**
 * 判断是否存在相同的中文名称
 */
var isExistProName = function (opType,proTitle,proName){
	var isExist = false;
	if(opType=='add'){
		$('#leftTable').find('tr').each(function(i,trNode){
			var tempProName = "";
			try{
				tempProName= $(trNode).find(">td div span").eq(2).html().replace(/(^\s*)|(\s*$)/g,'');
				if (proName == tempProName) {
					isExist = true;
					return false;
				}
			}catch(e){
				console.log("此异常属于正常现象，不处理！");
			}
		});
	}else if(opType =='update'){
		$('#leftTable').find('tr').each(function(i,trNode){
			var tempProName = "";
			var tempProTitle ="";
			try{
				tempProName= $(trNode).find(">td div span").eq(2).html().replace(/(^\s*)|(\s*$)/g,'');
				tempProTitle = $(trNode).find(">td").eq(1).html();
				if (proName == tempProName && tempProTitle !=proTitle) {
						isExist = true;
						return false;
				}
			}catch(e){
				console.log("此异常属于正常现象，不处理！");
			}
		});
	}
	
	return isExist;
}


/**
 * 追加新的节点前的判断
 * 
 * @param returnValue
 * @param className
 * @param classTitle
 * @param data
 * @returns
 */
var newNodeFun  = function (returnValue,className,classTitle,data){
	var hasClassTitle = returnValue.classTitle;
	var hasClassName = returnValue.className;
	if(hasClassTitle == true || hasClassName == true){
		if(hasClassTitle== true){
			$('#classTitleTr').addClass("errortd");
	    	$('#classTitleTr').find('td:last-child').find('div').html("与现有名称重复！");
		}
		if(hasClassName== true){
			$('#"classNameTr"').addClass("errortd");
	    	$('#"classNameTr"').find('td:last-child').find('div').html("与现有名称重复！");
		}
		return ;
	}
	var flag = returnValue.isSave;
	if(!flag){
		alert("保存出错，请检查网络或联系管理员！");
		return false;
	}
    document.getElementById('light').style.display='none';
    document.getElementById('fade').style.display='none';
// $('#classTitleTr').removeClass().val("");
// $('#classNameTr').removeClass().val("");
//    appendNode(data,className,classTitle);
    $("#submitForm").unbind("click");
    $('#classTitle').val("");
	$('#className').val("");
	$('#linkWide').val("");
	$('#linkType').val("");
	$('#shunxu').val("");
	$('#linkColor').val("");
	$('#relationDescr').val("");
	var opMenu = $(data).parent().parent().find('>td input[type="hidden"]').val().replace(/(^\s*)|(\s*$)/g, "");
//	opMenu = opMenu.substring(opMenu.lastIndexOf('.'));
//	alert(opMenu);
	refreshedModel(opMenu);
}
/**
 * 追加同辈节点
 * 
 * @param data
 * @returns
 */
//var appendNode = function (data,className,classTitle){
//	var tr = $(data).parent().parent();
//	var div = tr.children().first().find('>div');
//	var fullClassTitle = tr.children().first().find('input[type="hidden"]').val();
//	var tempTr =$('<tr>').hide();
//	var leftWidth = div.css('padding-left');
//	var linkColor = $('#linkColor').val().replace(/\s/g, "");
//	var linkWidth = $('#linkWide').val();
//	leftWidth = parseInt(leftWidth);
//	var td1  = '<td class="col"><input type="hidden" id="'+fullClassTitle+'.'+classTitle+'" value="'+fullClassTitle+'.'+classTitle+'"><div style="padding-left:'+((leftWidth/16)+1)+'em"><span class="spanl fuxuan"><input id="'+classTitle+'" value="'+classTitle+'" type="checkbox" onclick="checkBoxChoose(this);event.cancelBubble=true;"></span><span class="spanl tbimg"></span><span class="spanl tbname">'+className+'</span><span class="spanl"><a href="javascript:void(0);" class="tbedit" onclick="updateName(this);event.cancelBubble=true;"></a></span><span style="display:none" class="spanr" ><s class="tbdown"></s></span></div></td><td class="enCol">'+classTitle+'</td><td class="enCol">'+translation(classTitle)+'</td>';
//	
//	tempTr.append(td1);
//	var td2;
//	if((fullClassTitle+'.'+classTitle).indexOf('RelRelation.')==0){
//		// 关系模型
//		var td3 = $('<td class="gx_color">');
//        var input = $('<input id="'+classTitle+'_linkColor"  value="' + linkColor + '"/>');
//        td3.append(input);
//        tempTr.append(td3);
//        input.spectrum({
//            chooseText: "确定",
//            cancelText: "取消",
//            preferredFormat: "rgb",
//            showInput: true,
//            showPalette: true,
//            palette:[
//                ["#000000", "#434343", "#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3", "#ffffff"],
//                        ["#980000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#4a86e8", "#0000ff", "#9900ff", "#ff00ff"],
//                        ["#e6b8af", "#f4cccc", "#fce5cd", "#fff2cc", "#d9ead3", "#d9ead3", "#c9daf8", "#cfe2f3", "#d9d2e9", "#ead1dc"],
//                        ["#dd7e6b", "#ea9999", "#f9cb9c", "#ffe599", "#b6d7a8", "#a2c4c9", "#a4c2f4", "#9fc5e8", "#b4a7d6", "#d5a6bd"],
//                        ["#cc4125", "#e06666", "#f6b26b", "#ffd966", "#93c47d", "#76a5af", "#6d9eeb", "#6fa8dc", "#8e7cc3", "#c27ba0"],
//                        ["#a61c00", "#cc0000", "#e69138", "#f1c232", "#6aa84f", "#45818e", "#3c78d8", "#3d85c6", "#674ea7", "#a64d79"],
//                        ["#85200c", "#990000", "#b45f06", "#bf9000", "#38761d", "#134f5c", "#1155cc", "#0b5394", "#351c75", "#741b47"],
//                        ["#5b0f00", "#660000", "#783f04", "#7f6000", "#274e13", "#0c343d", "#1c4587", "#073763", "#20124d", "#4c1130"]
//                ],
//            hide: function(tinycolor) {
//// alert(tinycolor);
//            }
//        });
//		
//        td2 = '<td class="gx_wide"><input type="text" style="width:40px;" name="attribute_width" class="tbinpt" id="'+classTitle+'_width" value="'+linkWidth+'" onkeypress="return common.num_int(this,event)" onchange = "updateLinkWide(this,\'width\')"></td><td class="gx_ext">可扩展</td><td class="gx_opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'gxmx\')">属性维护</a><a href="javascript:void(0);"  onclick="maintainEnv(this)">适用环境</a></td>';
//	}else{
//		td2 = '<td class="opr"><a href="javascript:void(0);" onclick="newNode(this)">添加</a><a href="javascript:void(0);" onclick="deleteRow(this)">删除</a><a href="javascript:void(0);" onclick="propertiesDefend(this,\'\')">属性维护</a></td>';
//	}
//	tempTr.append(td2);
//    tr.after(tempTr);
//    div.attr('class','tbdiv');
//    div.find('span:last-child').css('display','block');
//    openOrCloseMenu(div[0]);
//}

/**
 * 检查要增加或修改的标题名称和类名称是否已经存在
 * 
 * @param className
 * @param classTitle
 */
function checkClassMessage(viewType,superClassTitle,className,classTitle,isSession,shunxu,group,linkColor,linkWide,linkType,relationDescr,data) {
	var userAccount = $('#userAccount').val();
	var basePath = $("#basePath").val();
  　　var url =basePath+"servlet/ClassCheckServlet";  
  	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		data:{"optionType":encodeURI("add"),
			"viewType":encodeURI(viewType),
			"superClassTitle":encodeURI(superClassTitle),
			"className":encodeURI(className),
			"classTitle":encodeURI(classTitle),
			"isSession":encodeURI(isSession),
			"shunxu":encodeURI(shunxu),
			"group":encodeURI(group),
			"linkColor":encodeURI(linkColor),
			"linkWide":encodeURI(linkWide),
			"linkType":encodeURI(linkType),
			"relationDescr":encodeURI(relationDescr),
			"userAccount":encodeURI(userAccount)},
		async: false,
		success:function(returnValue)
			{
			newNodeFun(returnValue,className,classTitle,data);
			},
		error:function(){
			alert("错误");	
		}
	});
};
/**
 * 将类标题翻译成表名称
 * 
 * @param str
 */
var translation = function (str){

	var temp = str.substr(0,3)+"_"+str.substr(3);
	return temp.toUpperCase();
};

/**
 * 加载要显示出来的所有的待选择的拓扑图标 显示拓扑图标带选项
 */
var getMenuPic = function (data){
    var val  = $("#menuPicOp").val();
    if(val ==1){
        $("#menuPicOp").val('0')
        $("#menuPic").hide();
    }else{
        $("#menuPicOp").val('1')
        $('#menuPic').append('<li><a href="javascript:void(0);"><img src="'+getCSSPath()+'modelMa/images/icon/mag20_1.png" ></a></li><li><a href="javascript:void(0);"><img src="'+getCSSPath()+'modelMa/images/icon/mag20_1.png"></a></li><li><a href="javascript:void(0);"><img src="'+getCSSPath()+'modelMa/images/icon/mag20_1.png"></a></li><li><a href="javascript:void(0);"><img src="'+getCSSPath()+'modelMa/images/icon/mag20_1.png"></a></li><li><a href="javascript:void(0);"><img src="'+getCSSPath()+'modelMa/images/icon/mag20_1.png"></a></li>');
        $('#menuPic').find('>li img').live('click',function(){
        	$("#menuPic").hide();
            var path  = this.src
            $("#currentPic").attr('src',path);
            $("#menuPicOp").val('0')
        });
        $("#menuPic").show();
    }
};


var trHeight = function (){
	 IFrameResizeByHeight("500px");
}
/**
 * 设置窗体高度
 * 
 * 
 */
var setTrWidth = function (){
//	var tempHeight =0;
//	$('#leftTable').find('tr').each(function(i,tr){
//		if($(tr).is(':visible')){
//			tempHeight += $(tr).height();
//		}
//	});
	var browser = $('#browser').height()+65;
	if(browser < 600){
		browser = 600;
	}
	IFrameResizeByHeight(browser+"px");
}

/**
 * 删除
 * 
 * @param data
 */
var deleteRow = function (data){
	var flag = confirm("确定删除吗？");
	if(!flag){
		return ;
	}
	var tr = $(data).parent().parent();
	var parVal = tr.children().first().find("input[type='hidden']").val();
	var nextTr = tr.nextAll('tr');
    var flag = false;
    nextTr.each(function (m, chilNode) {
        var chiVal = $(chilNode).find(">td input[type='hidden']").val();
        if (chiVal.indexOf(parVal+".") == 0 && 1 == compareCount(parVal, chiVal)) {
        	flag = true;
// break;
        	return false ;
        }
    });
    if(flag){
    	alert("请先删除子模型！");
    	return ;
    }
    var temParVal = parVal.substring(parVal.lastIndexOf(".")+1);
    var userAccount = $('#userAccount').val();
    var basePath = $("#basePath").val();
  　　var url =basePath+"servlet/DeleteServlet";  
  	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		data:{"classTitle":encodeURI(temParVal),
			"opClass":encodeURI('ResDefClass'),
			"userAccount":encodeURI(userAccount)},
		// contentType:"application/json;charset=utf-8",
		async: false,
		success:function(returnValue)
			{
			refurbishNode(returnValue,parVal,tr);
			},
		error:function(){
			alert("删除错误，请联系管理员！");	
		}
	});
};
/***
 * 检查是否删除成功
 */
var refurbishNode = function (returnValue,parVal,tr){
	var deleteType = returnValue.deletType;
	if(deleteType){
		var tempClassTitle = parVal.substring(0,parVal.lastIndexOf('.'));
		var flag = false;
		var parTr ;
		var classTitle ;
		parTr = tr.prev();
		while(flag == false){
			classTitle = parTr.find('> td input[type="hidden"').val();
			if(classTitle == tempClassTitle){
				// 找到父级tr
				flag = true;
			}else if(parTr == 'undefined' || parTr.length == 0){
				// 已经遍历到顶部没有找到父级，说明要删除的是顶级元素，不允许删除定义元素
				break; 
			}else{
				parTr = parTr.prev();
			}
		}
		
		if(flag){
			// 找到父级tr
			 var chiVal = $(parTr).find(">td input[type='hidden']").val();
			 var index = chiVal.lastIndexOf(".");
			 parVal = chiVal.substring(index+1);
		}else{
			parVal= getCurrentTopClass();
		}
		refreshedModel(parVal);
	}else{
		alert("存在资源配置项，不允许删除！");
	}
}

var getCurrentTopClass = function (){
	var viewType = $('#viewType').val();
	var classTitle ; 
	if(viewType =='gxmx'){
		classTitle ="RelRelation";
	}else if(viewType =='zydx'){
		classTitle ="ResObject";
	}else if(viewType =='zywd'){
		classTitle ="ResSuperDim";
	}else if(viewType =='wwb'){
		classTitle ="ResStructure";
	}
	return classTitle;
}
/**
 * 属性维护
 */
var propertiesDefend = function (data,opType){
	var classTitle = $(data).parent().parent().find('td').eq(1).html();
	var fullClassTitle = $(data).parent().parent().find('td').eq(0).find('input[type="hidden"]').val();
	var basePath = $("#basePath").val();
	var form = document.getElementById("univeiwform");
	form.action = basePath + "modelManager/propertyDefend.jsp?classTitle="+classTitle+"&opType="+opType+"&fullClassTitle="+fullClassTitle;
	form.method = 'POST';
	form.target = '_self';
	form.submit();
//	refreshedModel();
};
/**
 * 维护适用环境
 */
var maintainEnv = function(data){
	var count = $(data).parent().children('a').length;
	
	var classTitle = $(data).parent().parent().find('td').eq(1).html();
	var fullClassTitle = $(data).parent().parent().find('td').eq(0).find('input[type="hidden"]').val();
	var basePath = $("#basePath").val();
	var form = document.getElementById("univeiwform");
	if(count  == 4){
		form.action = basePath + "modelManager/appliEnvList.jsp?classTitle="+classTitle+"&fullClassTitle="+fullClassTitle+"&isConRel="+"1";
	}else{
		form.action = basePath + "modelManager/appliEnvList.jsp?classTitle="+classTitle+"&fullClassTitle="+fullClassTitle+"&isConRel="+"0";
	}
	
	form.method = 'POST';
	form.target = '_self';
	form.submit();
};

/**
 * 修改线条粗细、线条颜色、类名称
 */
var updateLinkWide = function(data,type) {
	var cur = $(data).attr("id");
	var classTitle  = cur.substring(0,cur.indexOf("_"+type));
	var updatePro ;
	var opClass ;
	var updateVal 
	if(type == 'width'){
		// 线条粗细修改
		opClass = 'ResDefExtRelation';
		updatePro = "linkThickness";
		updateVal = $(data).val().replace(/\s/g, "");
		if(updateVal == '') {
			updateVal = '0';
			$(data).val('0');
		}
	}else if(type=='linkColor'){
		// 线条颜色修改
		opClass = 'ResDefExtRelation';
		updatePro = "linkColor";
		updateVal = $(data).val().replace(/\s/g, "");
	}else if(type =='classDescr'){
		// 修改名称
		opClass = 'ResDefClass';
		updatePro = "classDescr";
		updateVal = $(data).val().replace(/\s/g, "");
	}
	
	var isUpdate = false;
	var basePath = $("#basePath").val();
  　　	var url =basePath+"servlet/UpdateClassServlet";  
  	var userAccount = $('#userAccount').val();
  	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		data:{"opClass":encodeURI(opClass),
			"classTitle":encodeURI(classTitle),
			"updatePro":encodeURI(updatePro),
			"updateVal":encodeURI(updateVal),
			"userAccount":encodeURI(userAccount)},
		async: false,
		success:function(returnValue)
			{
				isUpdate =  returnValue.newOrupdate;
			},
		error:function(){
			alert("错误");	
		}
	});
  	return isUpdate;
};

/**
 * 导出属性视图
 */
var exportPro = function (){
	var clsCon = [];
	var tr = $('#leftTable').find('tr');
	 tr.nextAll().each(function (i, trNode) {
		 var chilCheck = $(trNode).children('td:first-child').find('>div span input[type="checkbox"]').is(':checked');
		 if(chilCheck){
			 var childFullTitle = $(trNode).find('> td input[type="hidden"').val();
			 var clsTitle = childFullTitle.substring(childFullTitle.lastIndexOf('.')+1);
			 clsCon.push(clsTitle);
		 }
	 });
	 var count = clsCon.length;
	 if(count<=0){
		 alert("没有选择要导出的类模型！");
		 return;
	 }
	 
	 var basePath = $("#basePath").val();
	  var url =basePath+"servlet/ExportClassPropertyServlet?expCls="+encodeURI(clsCon.join(","));  
	 $("#exprot").attr('href',url);
};
/**
 * 刷新模型视图
 */
function refreshedModel(classTitle){
	var userAccount = $('#userAccount').val();
	var viewType = $('#viewType').val();
	var basePath = $("#basePath").val();
  　　var url =basePath+"servlet/RefurbishController";  
  	$.ajax({
		type:"POST",
		url:url,
		dataType:"json",
		data:{
			"viewType":encodeURI(viewType),
			"opClass":encodeURI("ResDefClass"),
			"userAccount":encodeURI(userAccount)},
		async: false,
		success:function(returnValue)
			{
			var temp = JSON.stringify(returnValue);
			$('#dataJson').val(temp);
			builderTh();
			var viewType = $('#viewType').val();
//			if(viewType == 'gxmx'){
				$('#leftTable tr').height(52);
//			}else{
//				$('#leftTable tr').height(52);
//			}
			if(classTitle ==''){
				//手动点击刷新
				classTitle = getCurrentTopClass();
			}
			opMenu(classTitle);
			setTrWidth();
			},
		error:function(){
			alert("错误");	
		}
	});
  	
}
